<template>
	<view style="height: 100%;">
		<z-paging :hide-empty-view="true" @onRefresh="onRefresh" :auto="false" ref="paging" :fixed="false"
			:show-console-error="false" :refresher-status.sync="refresherStatus" @query="queryList">

			<view slot="top">
				<u-navbar class="index-title" :is-back="false" title="救助圈•领养平台">
					<view @click="goChooseCity" class=" u-flex u-p-l-24 ">
						<u-image class="u-m-r-4" width="32rpx" height="32rpx" src="@/static/index/location.png">
						</u-image>
						<view class="city u-line-1">
							{{filter.city}}
						</view>
						<u-icon name="arrow-down-fill" size="16"></u-icon>
					</view>
				</u-navbar>
			</view>


			<!-- 轮播图和通知 -->
			<view class="u-p-t-28 u-p-r-28 u-p-l-28  bg-white">
				<u-swiper @click="goDetail" v-if="swiperList && swiperList.length" :list="swiperList">
				</u-swiper>
				<view class="u-flex u-p-t-16 u-p-b-16">
					<u-image class="u-m-r-16" width="16px" height="16px" src="@/static/index/notice.png">
					</u-image>
					<text>成功找家 | </text>
					<view class="u-flex-1">
						<u-notice-bar :volume-icon="false" v-if="noticeList && noticeList.length" mode="horizontal"
							type="none" :is-circular="false" :list="noticeList">
						</u-notice-bar>
					</view>
				</view>
			</view>

			<!-- 快速导航 -->
			<view class="bg-white u-m-t-20 u-m-b-20">
				<u-row>
					<u-col span="3" v-for="(item,index) in indexFastList" :key="item.name">
						<view @click="goFastDetail(item)" class="bg-white fast-item">
							<u-image width="42px" height="42px" :src="item.icon">
							</u-image>
							<text class="u-font-12 color-3 u-m-t-24">{{item.name}}</text>
						</view>
					</u-col>
				</u-row>
			</view>





			<!-- 自定义下拉刷新view -->
			<!-- <custom-refresher slot="refresher" :status="refresherStatus"></custom-refresher> -->

			<!-- 小程序中直接修改组件style为position: sticky;无效，需要在组件外层套一层view -->

			<!-- 分类 -->
			<view style="z-index: 100;position: sticky;top :-1px;">
				<view class="bg-white u-flex u-row-between u-p-r-28 border-b">
					<view style="width:500rpx;">
						<u-tabs-swiper active-color="#FFCF0B" ref="uTabs" :list="list" :current="current"
							@change="tabsChange" :is-scroll="false"></u-tabs-swiper>
					</view>
					<!-- 筛选 -->
					<view @click="showFilterModal = true" class="u-flex">
						<text class="u-m-r-14 u-font-14" :style="{color:showFilterModal?'#FFCF0B':'#808080'}">筛选</text>
						<u-image width="14px" height="14px" src="@/static/index/filter.png"></u-image>
					</view>
				</view>
			</view>

			<swiper :style="{height:swiperHeight[swiperCurrent] + 'px'}" class="swiper" :current="swiperCurrent"
				@transition="transition" @animationfinish="animationfinish">
				<swiper-item class="swiper-item" v-for="(item, index) in list" :key="index">
					<no-data v-if="dataList[index].length ===0" customClass="bg-f5"></no-data>
					<view class="item" v-for="(item,idx) in dataList[index]" :key="idx">
						<index-card :item="item"></index-card>
					</view>

				</swiper-item>
			</swiper>
		</z-paging>



		<!-- 筛选弹出层 -->
		<u-popup v-model="showFilterModal" mode="top">
			<scroll-view scroll-y class="filter-box">
				<view class="color-80 u-p-t-28 u-p-b-28 u-font-28">性别</view>
				<radio-button v-model="filter.pet_sex" :list="dict.pet_sex"></radio-button>

				<view class="color-80 u-p-t-28 u-p-b-28 u-font-28">年龄</view>
				<radio-button v-model="filter.age_stage" :list="ageList"></radio-button>

				<view class="color-80 u-p-t-28 u-p-b-28 u-font-28">体型</view>
				<radio-button v-model="filter.body_id" :list="dict.body"></radio-button>

				<view class="color-80 u-p-t-28 u-p-b-28 u-font-28">毛发</view>
				<radio-button v-model="filter.hair_id" :list="dict.hair"></radio-button>

				<view class="color-80 u-p-t-28 u-p-b-28 u-font-28">疫苗</view>
				<radio-button v-model="filter.vaccine_id" :list="dict.vaccine"></radio-button>

				<view class="color-80 u-p-t-28 u-p-b-28 u-font-28">绝育</view>
				<radio-button v-model="filter.sterilize_id" :list="dict.sterilize"></radio-button>

				<view class="u-m-b-28">
					<view class="color-80 u-p-t-28 u-p-b-28 u-font-28">驱虫</view>
					<radio-button v-model="filter.expelling_parasite_id" :list="dict.expelling_parasite">
					</radio-button>
				</view>
			</scroll-view>

			<view class="u-flex">
				<view @click="handleReset" class="btn border-t">
					重置
				</view>
				<view @click="filterSubmit" class="btn border-t ok">
					确定
				</view>

			</view>
		</u-popup>

		<u-tabbar :list="tabBar" active-color="#FFCF0B" inactive-color="#808080" :border-top="false"></u-tabbar>

	</view>


</template>

<script>
	import {
		indexFastList,
		ageList,
		tabBar
	} from '@/const';
	import noData from '@/components/noData/noData.vue'
	import indexCard from '@/components/indexCard/indexCard.vue'
	import radioButton from '@/components/radioButton/radioButton.vue';
	import indexSwiperItem from '@/components/indexSwiperItem/indexSwiperItem.vue';


	import {
		getAds,
		getSuccessCase,
		getIndexList
	} from '@/api/index';
	import {
		getUserInfo
	} from '@/api/user';

	import {
		getCommonDataDict,
	} from '@/api/common';

	export default {
		components: {
			noData,
			indexCard,
			radioButton,
			indexSwiperItem
		},
		data() {
			return {
				swiperList: [],
				noticeList: [],
				noticeListId: [],
				indexFastList,
				ageList,
				filter: {
					city: '',
					category_id: 0,
					pet_sex: 0,
					age_stage: 0,
					body_id: 0,
					hair_id: 0,
					vaccine_id: 0,
					sterilize_id: 0,
					expelling_parasite_id: 0
				},
				dict: {},
				dataList: [],
				showFilterModal: false,
				activeItemStyle: {
					background: '#FFCF0B',
					borderRadius: '4px',
				},


				refresherStatus: 0,
				list: [{
						name: '全部'
					},
					{
						name: '猫猫'
					},
					{
						name: '狗狗'
					},
					{
						name: '其他'
					}
				],
				current: 0,
				swiperCurrent: 0,
				swiperHeight: [],
				tabBar,
			}
		},
		onShow() {
			const selectCity = uni.getStorageSync('city');
			this.filter.city = selectCity ? selectCity.city_name : '成都市';
			const access_token = uni.getStorageSync('access_token');
			if (access_token) {
				this.getUserInfo();
			}
		},
		onShareAppMessage() {
			return {
				path: '/pages/index/index'
			}
		},
		mounted() {
			this.getAds(); // 轮播图
			this.getSuccessCase(); // 通知
			this.getBaseFilterData();
		},
		watch: {
			['filter.city'](newVal, oldVal) {
				this.swiperHeight = [];
				this.init();
			}
		},
		methods: {
			async getUserInfo() {
				const res = await getUserInfo();
				const count = res.data.message_unread;
				this.tabBar = tabBar.map((item, index) => {
					if (index === 3) {
						item.count = count;
					}
					return item;
				})
			},
			filterSubmit() {
				this.showFilterModal = false;
				this.onRefresh(); // 先清空
				this.queryList(1, 10);
			},
			handleReset() {
				this.reset();
				this.queryList(1, 10);
			},
			reset() {
				const selectCity = uni.getStorageSync('city');
				const city = selectCity ? selectCity.city_name : '成都市';
				this.filter = {
					city,
					pet_sex: 0,
					age_stage: 0,
					body_id: 0,
					hair_id: 0,
					vaccine_id: 0,
					sterilize_id: 0,
					expelling_parasite_id: 0
				};

			},
			onRefresh() {
				this.$set(this.dataList, this.swiperCurrent, []);
				this.$set(this.swiperHeight, this.swiperCurrent, 0);
			},
			async queryList(page, pageSize) {
				const postData = Object.assign({}, {
					page,
					pageSize,
					...this.filter,
					category_id: this.swiperCurrent,
				})
				const res = await getIndexList(postData);
				const newData = res.data.list;
				this.$refs.paging.complete(newData);

				const oldData = this.dataList[this.swiperCurrent];
				this.$set(this.dataList, this.swiperCurrent, oldData.concat(newData));
				console.log(this.dataList);

				let newHeight = newData.length * 144 + 10;
				if (newData.length === 0) {
					newHeight = 195; // 没有数据的高度
				}
				const oldHeight = this.swiperHeight[this.swiperCurrent];
				this.$set(this.swiperHeight, this.swiperCurrent, newHeight + oldHeight);
				console.log(this.swiperHeight);
				// this.reset();
			},

			// tabs通知swiper切换
			tabsChange(index) {
				this.swiperCurrent = index;
			},
			// swiper-item左右移动，通知tabs的滑块跟随移动
			transition(e) {
				let dx = e.detail.dx;
				this.$refs.uTabs.setDx(dx);
			},
			// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
			// swiper滑动结束，分别设置tabs和swiper的状态
			animationfinish(e) {
				let current = e.detail.current;
				this.$refs.uTabs.setFinishCurrent(current);
				this.swiperCurrent = current;
				this.current = current;
			},
			async getBaseFilterData() {
				const res = await getCommonDataDict();
				let dict = res.data;
				Object.entries(dict).forEach((item) => {
					const field = item[0];
					const obj = item[1];
					let objArr = [];
					if (field != "pet_age") {
						Object.entries(obj).forEach((sub) => {
							const id = sub[0] * 1;
							const name = sub[1];
							objArr.push({
								id,
								name,
							});
						});
					} else {
						objArr = obj;
					}
					dict[field] = objArr;
				});
				dict.pet_type = [{
					id: 0,
					name: '全部'
				}, ...dict.pet_type]

				dict.pet_sex = [{
					id: 0,
					name: '不限'
				}, ...dict.pet_sex];

				dict.body = [{
					id: 0,
					name: '不限'
				}, ...dict.body];

				dict.hair = [{
					id: 0,
					name: '不限'
				}, ...dict.hair];

				dict.vaccine = [{
					id: 0,
					name: '不限'
				}, ...dict.vaccine];

				dict.sterilize = [{
					id: 0,
					name: '不限'
				}, ...dict.sterilize];

				dict.expelling_parasite = [{
					id: 0,
					name: '不限'
				}, ...dict.expelling_parasite];


				this.dict = dict;

			},
			async getAds() {
				const res = await getAds();
				this.swiperList = res.data;
			},
			async getSuccessCase() {
				const res = await getSuccessCase();
				this.noticeListId = res.data;
				this.noticeList = res.data.map(item => item.message);
			},
			goChooseCity() {
				uni.navigateTo({
					url: '/pagesIndex/citySelect/citySelect'
				})
			},
			goDetail(index) {
				const swiper = this.swiperList[index];
				if (swiper.media_type === 2) { // 自定义内容
					uni.navigateTo({
						url: '/pagesIndex/notice/notice?id=' + swiper.id
					})
				} else {
					uni.navigateTo({
						url: '/pagesIndex/webView/webView?url=' + swiper.link
					})
				}
			},
			goFastDetail(item) {
				if (!item.page) {
					uni.showModal({
						title: '暂未开发',
						showCancel: false,
					})
				} else {
					uni.navigateTo({
						url: item.page
					})
				}
			},

			async init() {
				const postData1 = {
					page: 1,
					pageSize: 10,
					...this.filter,
					category_id: 0,
				}

				const postData2 = {
					page: 1,
					pageSize: 10,
					...this.filter,
					category_id: 1,
				}

				const postData3 = {
					page: 1,
					pageSize: 10,
					...this.filter,
					category_id: 2,
				}

				const postData4 = {
					page: 1,
					pageSize: 10,
					...this.filter,
					category_id: 3,
				}
				const res1 = await getIndexList(postData1);
				const res2 = await getIndexList(postData2);
				const res3 = await getIndexList(postData3);
				const res4 = await getIndexList(postData4);
				this.dataList = [
					res1.data.list,
					res2.data.list,
					res3.data.list,
					res4.data.list,
				]
				console.log(this.dataList);
				this.dataList.forEach((item) => {
					if (item.length === 0) {
						this.swiperHeight.push(195) // 没有数据的高度
					} else {
						this.swiperHeight.push(item.length * 144 + 10)
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	/* 注意，1、父节点需要固定高度，z-paging的height:100%才会生效 */
	/* 注意，2、请确保z-paging与同级的其他view的总高度不得超过屏幕宽度，以避免超出屏幕高度时页面的滚动与z-paging内部的滚动冲突 */

	/*如果有scoped，page的css设置建议放在App.vue中 */

	page,
	.content {
		height: 100%;
	}

	// .paging-content {
	// 	flex: 1;
	// 	height: 100%;
	// 	display: flex;
	// 	flex-direction: column;
	// }

	// .swiper {
	// 	flex: 1;
	// }


	.index-title {
		/deep/ .u-title {
			color: #333 !important;
		}
	}

	.city {
		max-width: 160rpx;
	}

	.btn {
		height: 40px;
		line-height: 40px;
		font-size: 14px;
		text-align: center;
		width: 50%;
	}

	.ok {
		background: #FFCF0B;
	}

	.filter-box {
		height: 1000rpx;
		box-sizing: border-box;
		padding: 28rpx 28rpx 0 28rpx;
	}

	.fast-item {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 20rpx 0;
	}

	.category {
		background-color: #fff;
		padding: 18px 14px 7px;
		display: flex;
		justify-content: space-between;
		border-bottom: 1rpx solid #ECECEC;

		.active {
			font-size: 16px;
			color: #333 !important;
			font-weight: bold;
			position: relative;

			&::before {
				position: absolute;
				content: '';
				width: 21px;
				height: 2px;
				background: #FFCF0B;
				border-radius: 2px;
				bottom: -8px;
				left: 50%;
				transform: translateX(-50%);
			}
		}
	}
</style>
